﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace PrimeFinder
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            int number;

            if (!int.TryParse(textBox1.Text, out number))
            {
                MessageBox.Show("Error reading number.");
                return;
            }

            int prime = PrimeFinder.FindPrimeAbove(number);
            MessageBox.Show(string.Format("The smallest prime above {0} is {1}.", number, prime));
            textBox1.Text = prime.ToString();
        }
    }

    static class PrimeFinder
    {
        public static bool IsPrime(int n)
        {
            for (int tester = (int)Math.Sqrt(n); tester > 1; tester--)
                if (n % tester == 0)
                    return false;
            return true;
        }

        public static int FindPrimeAbove(int n)
        {
            for (int tester = n + 1; ; tester++)
                if (IsPrime(tester))
                    return tester;
            throw new Exception("Prime not found exception.");
        }
    }
}
